package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Favorite;
import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.service.FavoriteService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.recipedb.recipedb.service.UserService;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.data.domain.Page;


import java.util.List;

@RestController
@RequestMapping("/api/favorites")
@RequiredArgsConstructor
public class FavoriteController {

    private final FavoriteService favoriteService;
    private final UserService userService; // 新增：注入UserService

    @PostMapping
    public ResponseEntity<?> addFavorite(
            @RequestParam Long userId,
            @RequestParam Long recipeId) {
        try {
            Favorite favorite = favoriteService.addFavorite(userId, recipeId);
            return ResponseEntity.ok(favorite);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @DeleteMapping
    public ResponseEntity<?> removeFavorite(
            @RequestParam Long userId,
            @RequestParam Long recipeId) {
        boolean removed = favoriteService.removeFavorite(userId, recipeId);
        if (removed) {
            return ResponseEntity.ok().body("取消收藏成功");
        } else {
            return ResponseEntity.badRequest().body("取消收藏失败，记录不存在");
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Favorite>> getFavoritesByUserId(@PathVariable Long userId) {
        List<Favorite> favorites = favoriteService.getFavoritesByUserId(userId);
        return ResponseEntity.ok(favorites);
    }

    @GetMapping("/user/{userId}/recipes")
    public ResponseEntity<List<Recipe>> getFavoriteRecipesByUserId(@PathVariable Long userId) {
        List<Recipe> recipes = favoriteService.getFavoriteRecipesByUserId(userId);
        return ResponseEntity.ok(recipes);
    }

    @GetMapping("/user/{userId}/total-count")
    public ResponseEntity<Long> getTotalFavoritesByUserId(@PathVariable Long userId) {
        Long total = favoriteService.getTotalFavoritesByUserId(userId);
        return ResponseEntity.ok(total);
    }

    // 核心搜索接口
    @GetMapping("/user/{userId}/search")
    public ResponseEntity<Page<Favorite>> searchFavorites(
            @PathVariable Long userId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tag,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String ingredient,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication) {

        // 1. 校验是否已登录
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new AccessDeniedException("请先登录后再查询收藏记录");
        }

        // 2. 解析Token对应的真实登录用户ID
        String loginUsername = authentication.getName();
        Long loginUserId = userService.getUserIdByUsername(loginUsername);
        if (loginUserId == null) {
            throw new AccessDeniedException("登录用户不存在");
        }

        // 3. 严格校验：只能查询自己的收藏记录
        if (!loginUserId.equals(userId)) {
            throw new AccessDeniedException("无权查询用户" + userId + "的收藏记录");
        }


        Page<Favorite> result = favoriteService.searchFavorites(
                userId,
                keyword,
                tag,
                category,
                ingredient,
                pageNum,
                pageSize
        );
        return ResponseEntity.ok(result);
    }



}